package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.fillCommonFields.FillCommonFieldsUpdate;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author
 * @Date 2024/4/28 20:08
 * @Description:
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private  DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        page.addOrder(new OrderItem("update_time", false));

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        // 这里简化处理，实际上需要通过JOIN或者其他方式来包含Category的name字段
        IPage<DishPageDTO> dishPageDTOPage = baseMapper.selectDishWithCategory(page, dishPageQueryDTO);

        // 页面结果封装，假设PageResult是一个自定义的分页结果类
        PageResult pageResult = new PageResult();
        pageResult.setTotal(dishPageDTOPage.getTotal());
        pageResult.setRecords(dishPageDTOPage.getRecords());

        return pageResult;

    }

    @Override
    public void deleteDishByids(List<Long> ids) {

        //判断需要删除的id中的菜品有没有在售状态的
        List<Dish> lists = lambdaQuery().eq(Dish::getStatus, 1).in(Dish::getId, ids).list();
        if (lists.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        log.info("没有在售的菜品");
        //判断要删除的菜品是否在套餐中
//        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>().in(SetmealDish::getDishId, ids));
          List<SetmealDish> setmealDishes=Db.lambdaQuery(SetmealDish.class).in(SetmealDish::getDishId, ids).list();
        if (setmealDishes.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        log.info("没有在套餐中的菜品");

        //删除菜品以及口味
        baseMapper.deleteBatchIds(ids);
        dishMapper.deleteBatchIds(ids);
    }

    @Override
    public void statusUpdate(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        FillCommonFieldsUpdate.AutoFill(dish);
        baseMapper.updateById(dish);
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //查询出菜品信息
        Dish dish=baseMapper.selectById(id);
        //查询出菜品相关口味信息
        List<DishFlavor> dishFlavorList=dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId,id));

        //转换成VO
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishVO) {
    //更新菜品数据
       Dish dish=new Dish();
       BeanUtils.copyProperties(dishVO,dish);
    //填充公共字段
       FillCommonFieldsUpdate.AutoFill(dish);
    //更新菜品
       baseMapper.updateById(dish);
    //删除菜品相关口味信息并且重新插入
       dishFlavorMapper.delete(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId,dish.getId()));
        // 准备批量插入的口味数据
        List<DishFlavor> flavorsToInsert = new ArrayList<>();
        if (dishVO.getFlavors() != null && !dishVO.getFlavors().isEmpty()) {
            for (DishFlavor flavor : dishVO.getFlavors()) {
                flavor.setDishId(dish.getId()); // 确保每个口味记录与当前菜品关联
                flavorsToInsert.add(flavor);
            }
        }

        // 批量插入口味信息
        if (!flavorsToInsert.isEmpty()) {
            dishFlavorMapper.insertBatchFlavor(flavorsToInsert);
        }

    }
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectList(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1));

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, d.getId()));
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        //根据分类id查询出对应的菜品信息
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        List<Dish> dishList = dishMapper.selectList(queryWrapper.eq(Dish::getCategoryId, categoryId));
        return dishList;
    }
}